package com.star.controller.interceptor;

import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

/**
 * @Author star
 * @Date 2023/3/30 15:36
 * @PackageName:com.star.controller.interceptor
 * @ClassName: LoginInterceptor
 * @Description: TODO
 * @Version 1.0
 * 拦截器,登录拦截,只拦截聊天界面,其他的界面可离线访问
 */
@Component
public class LoginInterceptor implements HandlerInterceptor {
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        //获取session
        HttpSession session = request.getSession();
        //获取session中的user
        String user = (String) session.getAttribute("user");
        System.out.println(user);
        //如果user不为空,则放行
        if (user!=null){
            return true;
        }
        //否则重定向到登录界面
        response.sendRedirect("/autologin.html");
        //返回
        return HandlerInterceptor.super.preHandle(request, response, handler);
    }


    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {
        HandlerInterceptor.super.postHandle(request, response, handler, modelAndView);
    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
        HandlerInterceptor.super.afterCompletion(request, response, handler, ex);
    }
}
